<template>
    <div class="user-info-wrapper">
        <el-card shadow="hover">
            <template #header>登录信息</template>
            <el-space :size="[40, 40]">
                <el-upload :show-file-list="false" :http-request="onUploadAvatarRequest">
                    <el-avatar :size="100" :src="admin.avatar" />
                </el-upload>

                <el-space direction="vertical" alignment="stretch" :size="[40, 40]">
                    <el-text class="hello-info" type="primary" size="large">
                        {{ `${admin.nickName ?? admin.userName}，${getTime()}好！欢迎回来！` }}
                    </el-text>
                    <el-space alignment="stretch" :size="[40, 40]">
                        <span>
                            <el-text type="info">登录地区：</el-text>
                            <el-text v-if="isFinished">{{ loginIpInfo.data.province + '-' + loginIpInfo.data.city }}</el-text>
                        </span>
                        <span>
                            <el-text type="info">登录Ip：</el-text>
                            <el-text v-if="isFinished">{{ loginIpInfo.data.ip }}</el-text>
                        </span>
                        <span>
                            <el-text type="info">登录时间：</el-text>
                            <el-text v-if="isFinished">{{ admin.lastLoginDateTime }}</el-text>
                        </span>
                    </el-space>
                </el-space>
            </el-space>
        </el-card>
        <el-card shadow="hover">
            <template #header>个人基本信息</template>
            <el-form :label-width="100">
                <div class="dialog-form-item-group">
                    <el-form-item label="姓名：">
                        <el-input v-if="isUpdateUserInfo" v-model="userInfoForm.name" placeholder="请输入姓名" clearable></el-input>
                        <el-text v-else type="info">{{ admin.name }}</el-text>
                    </el-form-item>
                    <el-form-item label="昵称：">
                        <el-input v-if="isUpdateUserInfo" v-model="userInfoForm.nickName" placeholder="请输入昵称" clearable></el-input>
                        <el-text v-else type="info">{{ admin.nickName }}</el-text>
                    </el-form-item>
                    <el-form-item label="描述：">
                        <el-input v-if="isUpdateUserInfo" type="textarea" v-model="userInfoForm.description" placeholder="请输入描述"></el-input>
                        <el-text v-else type="info">{{ admin.description }}</el-text>
                    </el-form-item>
                    <el-form-item>
                        <template v-if="isUpdateUserInfo">
                            <el-button @click="onCloseUpdateForm('UserInfo')">取消</el-button>
                            <el-button @click="onConfirmUpdateForm('UserInfo')" type="primary">确认</el-button>
                        </template>
                        <el-button v-else @click="onOpenUpdateForm('UserInfo')" type="primary">更新个人信息</el-button>
                    </el-form-item>
                </div>
            </el-form>
            <el-divider />
            <el-text type="info">账户安全</el-text>
            <el-divider border-style="dashed" />
            <div class="user-guard-box">
                <el-space direction="vertical" alignment="stretch">
                    <el-text type="info">账户密码</el-text>
                    <el-text type="info">当前密码强度：弱</el-text>
                </el-space>
                <el-button link type="primary" @click="onOpenUpdateForm('Password')">立即修改</el-button>
            </div>

            <el-divider border-style="dashed" />
            <div class="user-guard-box">
                <el-space :direction="isUpdatePhoneNumber ? 'horizontal' : 'vertical'" alignment="stretch">
                    <el-text type="info">密保手机</el-text>
                    <el-input v-if="isUpdatePhoneNumber" v-model="phoneNumber" placeholder="请输入新的手机号码" clearable></el-input>
                    <el-text v-else type="info">已绑定手机：{{ formatPhoneNumber(admin.phoneNumber as string) }}</el-text>
                </el-space>
                <el-space v-if="isUpdatePhoneNumber" direction="horizontal">
                    <el-button @click="onCloseUpdateForm('PhoneNumber')">取消</el-button>
                    <el-button :disabled="phoneNumber?.trim() === ''" @click="onConfirmUpdateForm('PhoneNumber')" type="primary">确认</el-button>
                </el-space>
                <el-button v-else link type="primary" @click="onOpenUpdateForm('PhoneNumber')">立即修改</el-button>
            </div>

            <el-divider border-style="dashed" />
            <div class="user-guard-box">
                <el-space :direction="isUpdateEmail ? 'horizontal' : 'vertical'" alignment="stretch">
                    <el-text type="info">密保邮箱</el-text>
                    <el-input v-if="isUpdateEmail" v-model="email" placeholder="请输入新的邮箱" clearable></el-input>
                    <el-text v-else type="info">已绑定邮箱：{{ formatEmail(admin.email as string) }}</el-text>
                </el-space>
                <el-space v-if="isUpdateEmail" direction="horizontal">
                    <el-button @click="onCloseUpdateForm('Email')">取消</el-button>
                    <el-button :disabled="email?.trim() === ''" @click="onConfirmUpdateForm('Email')" type="primary">确认</el-button>
                </el-space>
                <el-button v-else link type="primary" @click="onOpenUpdateForm('Email')">立即修改</el-button>
            </div>
        </el-card>
        <UpdatePasswordForm ref="updatePasswordFormRef"></UpdatePasswordForm>
    </div>
</template>

<script setup lang="tsx">
import { UpdateUserInfoForm } from '@/api/auth/user/type'
import { UploadRequestHandler, UploadRequestOptions } from 'element-plus'

type UpdateType = 'UserInfo' | 'PhoneNumber' | 'Email' | 'Password'

const { admin, getAdminUserInfo } = useAdminStore()

const isUpdateUserInfo = ref(false)
const isUpdatePhoneNumber = ref(false)
const isUpdateEmail = ref(false)

const email = ref(admin.email)
const phoneNumber = ref(admin.phoneNumber)
const userInfoForm = reactive<UpdateUserInfoForm>({
    id: admin.id as number,
    name: admin.name,
    nickName: admin.nickName,
    description: admin.description,
})
const updatePasswordFormRef = ref()

const { data: loginIpInfo, isFinished } = useFetch(CommonApi.Ip_Info_Url).json()

const onOpenUpdateForm = (action: UpdateType) => {
    switch (action) {
        case 'UserInfo':
            isUpdateUserInfo.value = true
            break
        case 'PhoneNumber':
            isUpdatePhoneNumber.value = true
            break
        case 'Email':
            isUpdateEmail.value = true
            break
        case 'Password':
            updatePasswordFormRef.value.onOpenDialog()
            break
        default:
            break
    }
}
const onCloseUpdateForm = (action: UpdateType) => {
    switch (action) {
        case 'UserInfo':
            isUpdateUserInfo.value = false
            break
        case 'PhoneNumber':
            isUpdatePhoneNumber.value = false
            break
        case 'Email':
            isUpdateEmail.value = false
            break
        default:
            break
    }
}

const onConfirmUpdateForm = async (action: UpdateType) => {
    switch (action) {
        case 'UserInfo':
            await onConfirmUpdateUserInfo()
            break
        case 'PhoneNumber':
            await onConfirmUpdatePhoneNumber()
            break
        case 'Email':
            await onConfirmUpdateEmail()
            break
        default:
            break
    }
}

// 修改用户信息
const onConfirmUpdateUserInfo = async () => {
    const result = await updateUserInfo(userInfoForm)
    if (result.isSuccess) {
        await getAdminUserInfo()
        window.location.reload()
        ElMessage.success('更新成功')
    } else {
        ElMessage.error('更新失败')
    }
}
// 修改手机
const onConfirmUpdatePhoneNumber = async () => {
    if (!phoneNumber.value?.match(/^\d{11}$/)) {
        ElMessage.warning('请输入正确手机号码')
        return
    }
    const result = await updatePhoneNumber(admin.id as number, phoneNumber.value as string)
    if (result.isSuccess) {
        admin.phoneNumber = phoneNumber.value
        isUpdatePhoneNumber.value = false
        ElMessage.success('更新成功')
    } else {
        ElMessage.error('更新失败')
    }
}
// 修改邮箱
const onConfirmUpdateEmail = async () => {
    if (!email.value?.includes('@')) {
        ElMessage.warning('请输入正确邮箱')
        return
    }
    const result = await updateEmail(admin.id as number, email.value as string)
    if (result.isSuccess) {
        admin.email = email.value
        isUpdateEmail.value = false
        ElMessage.success('更新成功')
    } else {
        ElMessage.error('更新失败')
    }
}
// 修改头像
const onUploadAvatarRequest = async (options: UploadRequestOptions): Promise<UploadRequestHandler | undefined> => {
    if (options.file.type !== 'image/jpeg' && options.file.type !== 'image/png' && options.file.type !== 'image/gif') {
        ElMessage.error('头像图片格式必须是 JPG | PNG | GIF ！')
        return
    } else if (options.file.size / 1024 / 1024 > 2) {
        ElMessage.error('头像图片大小不能超过2MB！')
        return
    }
    const result = await uploadFile(options.file)
    if (!result.isSuccess) {
        return
    }
    const result2 = await updateAvatar(admin.id as number, result.data.url)
    if (result2.isSuccess) {
        admin.avatar = result.data.url
    }
}
</script>

<style lang="scss" scoped>
.user-info-wrapper {
    margin: 20px;

    .el-card {
        &:nth-child(2) {
            margin-top: 20px;
        }
    }
    .hello-info {
        font-size: 30px;
    }

    .user-guard-box {
        display: flex;
        justify-content: space-between;
        align-items: flex-end;
    }
    .dialog-form-item-group {
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
    }
}
</style>
